package com.gumbo.bookmanager.controller.user;

import com.gumbo.bookmanager.mapper.BookMapper;
import com.gumbo.bookmanager.mapper.ReaderMapper;
import com.gumbo.bookmanager.mapper.RecordMapper;
import com.gumbo.bookmanager.pojo.Reader;
import com.gumbo.bookmanager.pojo.Record;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.SimpleFormatter;

@Controller
@RequestMapping("/user/record")
public class UserRecordController {
    @Autowired
    private RecordMapper recordMapper;
    @Autowired
    private ReaderMapper readerMapper;
    @Autowired
    private BookMapper bookMapper;

    @RequestMapping("/toOwnRecord")
    public String ownRecord(Model model, HttpSession httpSession){
        String username =(String)httpSession.getAttribute("username");
        List<Record>records =recordMapper.getOwnRecord(username);
        model.addAttribute("records",records);
        return"user/ownRecord";
    }
    @RequestMapping("/lendBook/{bookId}")
    public String lendBook(Model model, @PathVariable("bookId") String bId,HttpSession httpSession) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //获取当前时间
        String lendDate = dateFormat.format(new Date());
        Date lDate = dateFormat.parse(lendDate);
        //获取三个月后的时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MONTH,3);
        Date bDate = calendar.getTime();
        String backDate = dateFormat.format(bDate);

        long bookId = Long.parseLong(bId);
        int bookId2 = Integer.parseInt(bId);
        String bookName = bookMapper.getBookNameById(bookId2);
        String username =(String)httpSession.getAttribute("username");
        Reader reader = readerMapper.getReaderInfo(username);
        int readerId = reader.getReaderId();
        Record record = new Record(bookId,readerId,lendDate,backDate,bookName);
        recordMapper.lendBook(record);
        return "redirect:/user/record/toOwnRecord";
    }
}
